package cate.game.server.schedule.task;

import cate.game.GameBody;
import cate.game.role.Role;
import lombok.extern.slf4j.Slf4j;

import java.util.Collection;
import java.util.List;

@Slf4j
public class SaveDbTask extends ProcessTaskExecutable {

    @Override
    protected long timeoutMs() {
        return 120_000l;
    }

    @Override
    protected boolean cancelWhenTimeout() {
        return false;
    }

    @Override
    protected String exeImpl() throws Exception {
        StringBuilder sb = new StringBuilder();
        Collection<GameBody> gameList = games.getAll();
        int nRoleSuccess = 0;
        int nRoleFail = 0;
        for(GameBody game : gameList) {
            if(Thread.interrupted()) {
                log.warn("线程被中断，不再继续执行了，就此打住，ByeBye");
                break;
            }
            // 保存角色
            int nRoleSuccessGame = 0;
            int nRoleFailGame = 0;
            try {
                List<Role> roles = game.role.getActiveRoles();
                for(Role role : roles) {
                    try {
                        role.save();
                        log.info("保存角色成功 {}", (role != null?role.getUid():"Role(null)"));
                        nRoleSuccessGame++;
                        nRoleSuccess++;
                    } catch (Exception ee) {
                        nRoleFailGame++;
                        nRoleFail++;
                        log.error("保存角色错误", ee);
                    }
                }
            } catch (Exception e) {
                log.error("", e);
            }
            sb.append("S"+game.config.srvId+" role:"+nRoleSuccessGame+"√");
            if(nRoleFailGame > 0) {
                sb.append(nRoleFailGame+"×");
            }
            sb.append(";");

            // 保存协会
            int nGuild = game.res.guild.save();
            sb.append("协会"+nGuild+"个;");

            task.setResult(sb.toString());
            pc.console.processTask.update(task);
        }
        sb.append("nS="+gameList.size()+" ");
        sb.append("role:"+nRoleSuccess+"√");
        if(nRoleFail > 0) {
            sb.append(nRoleFail+"×");
        }
        sb.append(";");
        return sb.toString();
    }

}
